package YAPclient.sound;

import java.io.BufferedInputStream;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import YAPclient.DataModul;
import YAPenvironment.YAPconstant;

public class MusicClip implements ISound {

	private boolean paused = false;
	private Clip clip;
	
	public MusicClip(URL soundURL){
		try{
			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundURL);
			BufferedInputStream bufferedInputStream = new BufferedInputStream(audioInputStream);
			AudioFormat af = audioInputStream.getFormat();
			int size = (int) (af.getFrameSize() * audioInputStream.getFrameLength());
			byte[] audio = new byte[size];
			bufferedInputStream.read(audio, 0, size);

			//create new clip to be played
			clip =  AudioSystem.getClip(AudioSystem.getMixerInfo()[0]);
			try{
				clip.open(af, audio, 0, size);
			}catch(IllegalArgumentException e){
				clip =  AudioSystem.getClip(AudioSystem.getMixerInfo()[1]);
				clip.open(af, audio, 0, size);
			}

		}catch(Exception e){
			if(YAPconstant.C_DEBUG){
				e.printStackTrace(); 
				}
		}
	}
	@Override
	public void play() {
		if(DataModul.clPlayer.getSound()){
			try{			
				//maximimum number of clips of same waveform running. If all are in use then the first one is liberated and restarted.
				if(clip.isActive()){
					
				}else{
					clip.stop();
					clip.setFramePosition(0);
					clip.start();
					return;
				}
	        }catch(Exception e){
//	        	DataModul.clPlayer.setSound(false);
	        	if(YAPconstant.C_DEBUG){ 
	        		e.printStackTrace();
	        		}
	        }
		}
	}

	@Override
	public void pause() {
		if(clip.isActive()){
			clip.stop();
			paused = true;
		}
	}

	@Override
	public void clear() {
		clip.stop();
		clip.setFramePosition(0);
	}
	@Override
	public void resume() {
		if(paused){
			clip.start();
			paused = false;
		}
	}

}
